<template>
  <view class="container">
    <tech-nav-bar title="消息" :currentPage="'/pages/technician/message'"></tech-nav-bar>
    
     <view class="message-container">
      <!-- 消息分类卡片 -->
      <view class="message-cards">
        <!-- 平台客服卡片 -->
        <view class="card service-card" @tap="goToService">
          <view class="card-left">
            <image class="service-avatar" src="/static/icon/一对一_one-to-one.svg" mode="aspectFill"></image>
            <view class="card-text">
            <text class="card-title">平台客服</text>
            <text class="card-desc">24h服务</text>
            </view>
          </view>
        </view>

        <!-- 平台公告卡片 -->
        <view class="card notice-card" @tap="goToNotice">
          <view class="card-left">
            <image class="notice-avatar" src="/static/icon/上传日志_upload-logs.svg" mode="aspectFill"></image>
            <view class="card-text">
            <text class="card-title">平台公告</text>
            <text class="card-desc">推送发布</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 所有通知列表 -->
      <view v-for="(notice, index) in notices" :key="index" class="system-notice" @tap="viewNoticeDetail(notice.id)">
        <view class="notice-header">
          <view class="notice-icon" :class="'level-' + notice.noticeLevel">
            <image class="notice-img" :src="getNoticeIcon(notice.noticeLevel)" mode="aspectFit"></image>
          </view>
          <text class="notice-title">{{ notice.noticeTitle }}</text>
          <text class="notice-time">{{ formatDate(notice.createTime) }}</text>
        </view>
        <view class="notice-content">
          <text class="notice-text">{{ getNoticePreview(notice.noticeContent) }}</text>
        </view>
      </view>
      
      <!-- 没有通知时的提示 -->
      <view class="empty-notice" v-if="notices.length === 0">
        <image src="/static/empty.png" mode="aspectFit"></image>
        <text>暂无通知</text>
      </view>
    </view>

    <!-- 客服弹窗 -->
    <view class="service-popup" v-if="showServicePopup">
      <view class="popup-mask" @tap="closeServicePopup"></view>
      <view class="popup-content">
        <view class="phone-info">{{ servicePhone }}可能是一个电话号码，你可以</view>
        <view class="action-list">
          <view class="action-item" @tap="makePhoneCall">呼叫</view>
          <view class="action-item" @tap="copyPhoneNumber">复制号码</view>
          <view class="action-item" @tap="addToContacts">添加到手机通讯录</view>
          <view class="action-item cancel" @tap="closeServicePopup">取消</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import TechNavBar from '@/components/tech-nav-bar.vue'
import jweixin from 'jweixin-module'

export default {
  components: {
    TechNavBar
  },
  data() {
    return {
      notices: [], // 所有通知
      userInfo: null, // 用户信息
      techId: '',
      // 通知图标映射
      noticeIcons: {
        1: '/static/icon/上传日志_upload-logs.svg', // 普通通知
        2: '/static/icon/上传1_upload-one.svg',     // 重要通知
        3: '/static/icon/上传2_upload-two.svg'      // 紧急通知
      },
      isJssdkInitialized: false,
      showServicePopup: false,
      servicePhone: '',
      isIOS: false
    }
  },
  onLoad() {
    // iOS 首次进入自动刷新
    // this.isIOS = /iPhone|iPad|iPod/i.test(navigator.userAgent);
    // if (this.isIOS && !sessionStorage.getItem('iosRefreshed_technicianMessage')) {
    //   sessionStorage.setItem('iosRefreshed_technicianMessage', 'true');
    //   window.location.reload();
    //   return;
    // }
    this.loadNotices();
    this.getServicePhone();
  },
  // 页面显示时刷新通知
  onShow() {
    // 初始化JSSDK
    this.initJssdkConfig();
    this.loadNotices();
  },
  methods: {
    // 初始化JSSDK配置
    initJssdkConfig() {
      // 获取当前页面URL（去除hash部分）
      const url = window.location.href.split('#')[0];
      
      // 请求后端获取签名配置
      uni.request({
        url: `${uni.$config.baseUrl}/wx/jssdk/config`,
        method: 'GET',
        data: { url: url },
        header: {
          'Authorization': uni.getStorageSync('token')
        },
        success: (res) => {
          if (res.data && res.data.code === 200) {
            const config = res.data.data;
            this.configJweixin(config);
          } else {
            uni.showToast({
              title: res.data?.msg || '获取配置失败',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          console.error('获取JSSDK配置失败:', err);
          uni.showToast({
            title: '获取微信配置失败',
            icon: 'none'
          });
        }
      });
    },
  // 配置jweixin
  configJweixin(config) {
      jweixin.config({
        debug: false, // 开启调试模式
        appId: config.appId, // 必填，公众号的唯一标识
        timestamp: config.timestamp, // 必填，生成签名的时间戳
        nonceStr: config.nonceStr, // 必填，生成签名的随机串
        signature: config.signature, // 必填，签名
        jsApiList: [
          'updateAppMessageShareData', // 分享给朋友
          'updateTimelineShareData', // 分享到朋友圈
          'showOptionMenu', // 显示右上角菜单
          'hideOptionMenu', // 隐藏右上角菜单
          'onMenuShareAppMessage', // 分享给朋友（旧接口）
          'onMenuShareTimeline', // 分享到朋友圈（旧接口）
          'scanQRCode', // 扫一扫接口
          'openCustomerServiceChat' // 打开客服会话
        ] // 必填，需要使用的JS接口列表
      });
      
      // 配置成功回调
      jweixin.ready(() => {
        console.log('jweixin配置成功');
        this.isJssdkInitialized = true;
        
        // 设置分享信息
        this.setShareInfo();
      });
      
      // 配置失败回调
      jweixin.error((err) => {
        console.error('jweixin配置失败:', err);
        uni.showToast({
          title: '微信配置失败',
          icon: 'none'
        });
      });
    },
    // 加载通知列表
    async loadNotices() {
      try {
        // 获取技师ID
        const userInfo = uni.getStorageSync('userInfo')
        this.techId = userInfo ? userInfo.techId || '' : ''
        console.log('技师ID:', this.techId)
        // 获取全部用户的通知 (target_type=1)
        const generalRes = await uni.request({
          url: `${uni.$config.baseUrl}/notice/notice/listAll`,
          method: 'GET',
          data: {
            targetType: 1,
			payStatus: 2,
          }
        });
        
        // 获取特定技师的通知 (target_type=2)
        const technicianRes = await uni.request({
          url: `${uni.$config.baseUrl}/notice/notice/listAll`,
          method: 'GET',
          data: {
			payStatus: 2,
            targetType: 2,
            targetIds: this.techId || ''
          }
        });
        
        let generalNotices = [];
        let technicianNotices = [];
        
        // 处理全部用户通知
        if (generalRes.data.code === 200) {
          generalNotices = generalRes.data.rows || [];
        } else {
          console.error('获取全部用户通知失败:', generalRes.data);
        }
        
        // 处理特定技师通知
        if (technicianRes.data.code === 200) {
          technicianNotices = technicianRes.data.rows || [];
        } else {
          console.error('获取技师特定通知失败:', technicianRes.data);
        }
        
        // 合并通知列表，技师特定通知排在前面
        this.notices = [...technicianNotices, ...generalNotices];
        
        // 按创建时间排序，最新的在前面
        this.notices.sort((a, b) => new Date(b.createTime) - new Date(a.createTime));
        
      } catch (err) {
        console.error('获取通知列表失败:', err);
        uni.showToast({
          title: '获取通知列表失败',
          icon: 'none'
        });
      }
    },
    
    // 获取通知内容预览（去除HTML标签，截取前30个字符）
    getNoticePreview(content) {
      if (!content) return ''
      // 移除HTML标签
      const plainText = content.replace(/<[^>]+>/g, '')
      // 截取前30个字符
      return plainText.length > 30 ? plainText.substring(0, 30) + '...' : plainText
    },
    
    // 查看通知详情
    viewNoticeDetail(id) {
      uni.navigateTo({
        url: `/pages/technician/message-detail?id=${id}`
      })
    },
    
    // 服务相关方法
    goToService() {
      this.showServicePopup = true;
    },
    
    // 关闭客服弹窗
    closeServicePopup() {
      this.showServicePopup = false;
    },
    
    // 获取客服电话
    getServicePhone() {
      uni.request({
        url: `${uni.$config.baseUrl}/system/config/configKey/CustomerServicePhone`,
        method: 'GET',
        success: (res) => {
          if (res.statusCode === 200 && res.data.code === 200) {
            this.servicePhone = res.data.msg || '' // 如果获取失败，使用默认值
          } else {
            console.error('获取客服电话失败:', res.data)
            this.servicePhone = '18655195062' // 使用默认值
          }
        },
        fail: (err) => {
          console.error('请求客服电话失败:', err)
          this.servicePhone = '18655195062' // 使用默认值
        }
      })
    },
    
    // 拨打电话
    makePhoneCall() {
      if (this.servicePhone) {
        uni.makePhoneCall({
          phoneNumber: this.servicePhone,
          success: () => {
            console.log('拨打电话成功');
          },
          fail: (err) => {
            console.error('拨打电话失败:', err);
            uni.showToast({
              title: '拨打电话失败',
              icon: 'none'
            });
          }
        });
      }
    },
    
    // 复制电话号码
    copyPhoneNumber() {
      if (this.servicePhone) {
        uni.setClipboardData({
          data: this.servicePhone,
          success: () => {
            uni.showToast({
              title: '复制成功',
              icon: 'success'
            });
          },
          fail: (err) => {
            console.error('复制失败:', err);
            uni.showToast({
              title: '复制失败',
              icon: 'none'
            });
          }
        });
      }
    },
    
    // 添加到通讯录
    addToContacts() {
      if (this.servicePhone) {
        uni.addPhoneContact({
          phoneNumber: this.servicePhone,
          success: () => {
            console.log('添加联系人成功');
          },
          fail: (err) => {
            console.error('添加联系人失败:', err);
            uni.showToast({
              title: '添加联系人失败',
              icon: 'none'
            });
          }
        });
      }
    },
    
    goToNotice() {
      uni.navigateTo({ url: '/pages/technician/notice' })
    },
    
    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return ''
      
      const now = new Date()
      const date = new Date(dateStr)
      const diffMs = now - date
      const diffMins = Math.floor(diffMs / 60000)
      const diffHours = Math.floor(diffMins / 60)
      const diffDays = Math.floor(diffHours / 24)
      
      // 今天内的消息显示时:分
      if (diffDays < 1) {
        const hours = date.getHours().toString().padStart(2, '0')
        const minutes = date.getMinutes().toString().padStart(2, '0')
        return `${hours}:${minutes}`
      } 
      // 昨天的消息
      else if (diffDays === 1) {
        return '昨天'
      }
      // 一周内的消息显示周几
      else if (diffDays < 7) {
        const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
        return weekDays[date.getDay()]
      } 
      // 其他显示年-月-日
      else {
        const year = date.getFullYear()
        const month = (date.getMonth() + 1).toString().padStart(2, '0')
        const day = date.getDate().toString().padStart(2, '0')
        return `${year}-${month}-${day}`
      }
    },
    
    // 根据通知级别获取对应的图标
    getNoticeIcon(level) {
      return this.noticeIcons[level] || this.noticeIcons[1];
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  padding: 0 0 100rpx;  /* 为顶部标题和底部导航栏留出空间 */
}

.message-container {
  min-height: 100vh;
  background: #F8F8F8;

  .page-header {
    padding: 20rpx 30rpx;
    background: #FFFFFF;

    .title {
      font-size: 40rpx;
      font-weight: bold;
      color: #333;
    }
  }

  .message-cards {
    padding: 20rpx;
    display: flex;
    gap: 20rpx;

    .card {
      flex: 1;
      background: #FFFFFF;
      border-radius: 16rpx;
      padding: 30rpx;
      position: relative;
      box-shadow: 0 8rpx 16rpx rgba(0, 0, 0, 0.08);
      transition: all 0.3s ease;

      &:active {
        transform: scale(0.98);
        box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.05);
      }

      .card-left {
        display: flex;
        align-items: center;
      }

      .service-avatar, .notice-avatar {
        width: 96rpx;
        height: 96rpx;
        border-radius: 48rpx;
        margin-right: 24rpx;
        flex-shrink: 0;
        background: rgba(255, 255, 255, 0.8);
        padding: 16rpx;
        display: flex;
        align-items: center;
        justify-content: center;
      }
      
      .service-card .service-avatar {
        filter: invert(45%) sepia(66%) saturate(2848%) hue-rotate(198deg) brightness(98%) contrast(101%);
      }
      
      .notice-card .notice-avatar {
        filter: invert(45%) sepia(66%) saturate(2848%) hue-rotate(198deg) brightness(98%) contrast(101%);
      }

      .card-text {
        display: flex;
        flex-direction: column;
      }

      .card-title {
        font-size: 38rpx;
        color: #2B87FF;
        font-weight: 600;
        margin-bottom: 10rpx;
      }

      .card-desc {
        font-size: 30rpx;
        color: rgba(43, 135, 255, 0.7);
      }

      .card-right {
        position: absolute;
        top: 20rpx;
        right: 20rpx;
      }
    }

    .service-card {
      background: linear-gradient(135deg, #F0F7FF 30%, #E1EEFF 100%);
      border-left: 6rpx solid #2B87FF;
    }

    .notice-card {
      background: linear-gradient(135deg, #F0F7FF 30%, #E1EEFF 100%);
      border-left: 6rpx solid #2B87FF;
    }
  }

  .system-notice {
    margin: 20rpx;
    background: #FFFFFF;
    border-radius: 12rpx;
    padding: 20rpx;
    margin-bottom: 40rpx;

    .notice-header {
      display: flex;
      align-items: center;
      margin-bottom: 10rpx;

      .notice-icon {
        width: 66rpx;
        height: 66rpx;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 20rpx;
        
        &.level-1 {
          background: #2B85E4;
        }
        
        &.level-2 {
          background: #FF9900;
        }
        
        &.level-3 {
          background: #FF4B4B;
        }
        
        .notice-img {
          width: 40rpx;
          height: 40rpx;
          filter: brightness(0) invert(1); /* 将图标颜色改为白色 */
        }
      }

      .notice-title {
        font-size: 32rpx;
        color: #333;
        flex: 1;
      }

      .notice-time {
        font-size: 28rpx;
        color: #999;
        margin-right: 20rpx;
      }
    }

    .notice-content {
      padding-left: 100rpx;

      .notice-text {
        font-size: 30rpx;
        color: #666;
        line-height: 1.6;
      }
    }
  }

  .unread-badge {
    background: #FF4B4B;
    color: #FFFFFF;
    font-size: 24rpx;
    padding: 2rpx 10rpx;
    border-radius: 20rpx;
    min-width: 20rpx;
    text-align: center;
  }

  .empty-notice {
    margin: 100rpx auto;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    
    image {
      width: 200rpx;
      height: 200rpx;
      margin-bottom: 20rpx;
    }
    
    text {
      font-size: 32rpx;
      color: #999;
    }
  }
}

.service-popup {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1000;
  
  .popup-mask {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.6);
  }
  
  .popup-content {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    background: #FFFFFF;
    border-radius: 24rpx 24rpx 0 0;
    overflow: hidden;
    box-shadow: 0 -8rpx 30rpx rgba(0, 0, 0, 0.15);
    
    .phone-info {
      padding: 45rpx 30rpx;
      font-size: 36rpx;
      color: #333;
      text-align: center;
      border-bottom: 1rpx solid #F5F5F5;
      font-weight: 500;
    }
    
    .action-list {
      display: flex;
      flex-direction: column;
      padding: 35rpx;
      
      .action-item {
        height: 100rpx;
        line-height: 100rpx;
        text-align: center;
        font-size: 34rpx;
        color: #2B87FF;
        background: #F0F7FF;
        border-radius: 50rpx;
        margin-bottom: 24rpx;
        font-weight: 500;
        transition: all 0.2s;
        
        &:active {
          background: #E1EEFF;
          transform: scale(0.98);
        }
        
        &:last-child {
          margin-bottom: 0;
        }
        
        &.cancel {
          background: #F5F5F5;
          color: #999;
          margin-top: 20rpx;
        }
      }
    }
  }
}
</style> 